from info import db
from . import order_blue
from info.utils.comments import login_required
from info.models import Order,House
from flask import g,jsonify,request,current_app
from info.utils.response_code import RET
import datetime

@order_blue.route('/orders',methods=['GET','POST','PUT'])
@login_required
def fnOrders():
    user = g.user
    if not user:
       return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    if request.method=='GET':
        role=request.args.get('role')
        user_id = user.id
        if role not in['custom','landlord']:
            return jsonify(errno=RET.DATAERR,errmsg='数据类型错误')

        if role=='custom':
            try:
                orders = Order.query.filter(Order.user_id==user_id).order_by(Order.create_time.desc()).all()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR,errmsg='读取订单信息失败')
        else:
            try:
                houses = House.query.filter(House.user_id==user_id).all()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR,errmsg='读取房源信息失败')
            if not houses:
                return jsonify(errno=RET.NODATA,errmsg='无房源信息')

            house_id=[]
            for house in houses:
                house_id.append(house.id)
            try:
                orders = Order.query.filter(Order.house_id.in_(house_id)).order_by(Order.create_time.desc()).all()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR,errmsg='读取订单信息失败')
            print(orders)

        order_list=[]
        for order in orders:
            order_list.append(order.to_dict())

        data = {
            'orders':order_list
        }
        return jsonify(errno=RET.OK,errmsg='OK',data=data)




    if request.method=='POST':
        house_id = request.json.get('house_id')
        start_date = request.json.get('start_date')
        end_date = request.json.get('end_date')

        if not all(['house_id','start_date','end_date']):
            return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

        try :
            house_id = int(house_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR,errmsg='数据类型错误')

        try:
            d1 = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            d2 = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            total_days = (d2-d1).days
            if total_days==0:
                total_days=1
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR,errmsg='数据类型错误')

        try:
            house = House.query.filter(House.id==house_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='获取房间信息失败')
        if not house:
            return jsonify(errno=RET.DATAERR, errmsg='无此房间数据')

        filter = house.max_days<total_days if house.max_days!=0 else False
        if house.min_days>total_days or filter:
            return jsonify(errno=RET.PARAMERR,errmsg='入住天数不符合要求')

        price = house.price

        order = Order()
        order.user_id = user.id
        order.house_id = house_id
        order.begin_date = d1
        order.end_date = d2
        order.days = total_days
        order.house_price = price
        order.amount = price * total_days


        try:
            db.session.add(order)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='存储订单信息失败')



        data={
            'order_id':order.id
        }
        return jsonify(errno=RET.OK,errmsg='OK',data = data)

    if request.method=='PUT':
        action = request.json.get('action')
        order_id = request.json.get('order_id')
        reason = request.json.get('reason')

        if not all(['action','order_id']):
            return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

        if action not in ['accept','reject']:
            return jsonify(errno=RET.DATAERR,errmsg='数据范围错误')

        try:
            order_id = int(order_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR,errmsg='数据类型错误')

        try:
            house = House.query.filter(House.id==Order.house_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='获取房间信息失败')
        if not house:
            return jsonify(errno=RET.DATAERR, errmsg='无此房间数据')

        try:
            order = Order.query.filter(Order.id==order_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='读取订单数据失败')
        if not order:
            return jsonify(errno=RET.DATAERR,errmsg='无此订单数据')

        if action=='accept':
            order.status = 'WAIT_COMMENT'
            house.order_count +=1


        if action=='reject':
            order.status = 'REJECTED'
            order.comment = reason if reason else None

        try:
            db.session.add(order,house)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='存储订单状态失败')

        return jsonify(errno=RET.OK,errmsg='OK')


@order_blue.route('/orders/comment', methods = ['PUT'])
@login_required
def order_comment():
    """
    订单评论 和 回复评论
    1. 判断用户是否登录
    2. 获取参数 comment , order_id
    3. 检查参数的完整性,comment , order_id
    4. 转换参数的类型,需要判断 order_id 是否存在
    5. 根据订单ID 查询订单数据
    6. 判断查询结果
    7. 构造模型类对象Comment, 保存订单评论数据
    8. 提交数据到mysql
    9. 返回评论数据
    :return:
    """
    # 尝试获取用户信息
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录')
    # 获取参数
    comment = request.json.get('comment')
    order_id = request.json.get('order_id')
    # 检查参数的完整性
    if not all([comment,order_id]):
        return jsonify(errno = RET.PARAMERR,errmsg='参数缺失')
    # 转换参数的数据类型
    try:
        order_id = int(order_id)
    except Exception as  e:
        return jsonify(errno=RET.PARAMERR,errmsg='参数类型错误')
    # 根据订单id查询数据库
    try:
        orders = Order.query.get(order_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询订单数据失败')
    # 判断查询数据
    if not orders:
        return jsonify(errno=RET.NODATA,errmsg='无订单数据')
    # 构造模型类对象,保存订单评论数据
    orders.comment = comment
    orders.status = 'COMPLETE'
    # 提交数据到mysql
    try:
        db.session.add(orders)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存评论数据失败')

    # 返回数据
    return jsonify(errno=RET.OK,errmsg='OK')